package com.stars.pao.aicloud.controller;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.stars.pao.aicloud.entity.User;
import com.stars.pao.aicloud.entity.dto.UserDTO;
import com.stars.pao.aicloud.service.IUserService;
import com.stars.pao.aicloud.util.NameUtil;
import com.stars.pao.aicloud.util.ResponseEntity;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;


@Tag(name = "用户控制器")
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private IUserService userService;
    @Value("${jwt.secret}")
    private String jwtSecret;

    @Operation(summary = "登录请求")
    @Parameters({
            @Parameter(name = "userDTO",description = "用户对象"),
            @Parameter(name = "captcha",description = "验证码信息"),
            @Parameter(name = "request",description = "请求")
    })
    //登录方法
    @PostMapping("/login")
    public ResponseEntity login(@Validated UserDTO userDTO, String captcha, HttpServletRequest request) {
//        不用判断了，加了验证框架
//       1.非空判断
//        if(!StringUtils.hasLength(username) || !StringUtils.hasLength(password)
//        || !StringUtils.hasLength(captcha)) {
//            输出内容为空
//            return ResponseEntity.fail("参数有误！");
//        }

//        2.验证图片验证码
        String redisCaptchaKey = NameUtil.getCaptchaName(request);
        String captchaCode = (String) redisTemplate.opsForValue().get(redisCaptchaKey);
        if(!StringUtils.hasLength(captchaCode) || !captchaCode.equalsIgnoreCase(userDTO.getCaptcha())) {
            return ResponseEntity.fail("验证码错误！");
        }

//        3.用户名和密码判断
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", userDTO.getUsername());
        User user = userService.getOne(queryWrapper);
        if(user != null && passwordEncoder.matches(userDTO.getPassword(),
                user.getPassword())) {
//            生成jwt
            Map<String,Object> payload = new HashMap<>();
            payload.put("uid", user.getUid());
            payload.put("username", user.getUsername());
//            前端要显示username
            Map<String,String> result = new HashMap<>();
            result.put("jwt", JWTUtil.createToken(payload, jwtSecret.getBytes()));
            result.put("username", user.getUsername());
            return ResponseEntity.succ(result);
        }
//        if("admin".equals(userDTO.getUsername()) && "123456".equals(userDTO.getPassword())) {
//            登录成功
//            return ResponseEntity.succ("登录成功");
//        }
        return ResponseEntity.fail("用户名或密码不正确！");

    }

    @PostMapping("/register")
    public ResponseEntity add(@Validated User user) {
        //1.将密码进行加盐处理
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        //2.添加方法
        boolean result = userService.save(user);
        if(result) {
            return ResponseEntity.succ("添加成功");
        }
        return ResponseEntity.fail("未知错误！");
    }
}
